// This source file is part of the polarphp.org open source project
//
// Copyright (c) 2017 - 2019 polarphp software foundation
// Copyright (c) 2017 - 2019 zzu_softboy <zzu_softboy@163.com>
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://polarphp.org/LICENSE.txt for license information
// See https://polarphp.org/CONTRIBUTORS.txt for the list of polarphp project authors
//
// Created by polarboy on 2018/06/04.

/*
 * Copyright 2001-2004 Unicode, Inc.
 *
 * Disclaimer
 *
 * This source code is provided as is by Unicode, Inc. No claims are
 * made as to fitness for any particular purpose. No warranties of any
 * kind are expressed or implied. The recipient agrees to determine
 * applicability of information provided. If this file has been
 * purchased on magnetic or optical media from Unicode, Inc., the
 * sole remedy for any claim will be exchange of defective media
 * within 90 days of receipt.
 *
 * Limitations on Rights to Redistribute This Code
 *
 * Unicode, Inc. hereby grants the right to freely use the information
 * supplied in this file in the creation of products supporting the
 * Unicode Standard, and to make copies of this file in any form
 * for internal or external distribution as long as this notice
 * remains attached.
 */

/* ---------------------------------------------------------------------

    Conversions between Utf32, UTF-16, and UTF-8.  Header file.

    Several funtions are included here, forming a complete set of
    conversions between the three formats.  UTF-7 is not included
    here, but is handled in a separate source file.

    Each of these routines takes pointers to input buffers and output
    buffers.  The input buffers are const.

    Each routine converts the text between *sourceStart and sourceEnd,
    putting the result into the buffer between *targetStart and
    targetEnd. Note: the end pointers are *after* the last item: e.g.
    *(sourceEnd - 1) is the last item.

    The return result indicates whether the conversion was successful,
    and if not, whether the problem was in the source or target buffers.
    (Only the first encountered problem is indicated.)

    After the conversion, *sourceStart and *targetStart are both
    updated to point to the end of last text successfully converted in
    the respective buffers.

    Input parameters:
        sourceStart - pointer to a pointer to the source buffer.
                The contents of this are modified on return so that
                it points at the next thing to be converted.
        targetStart - similarly, pointer to pointer to the target buffer.
        sourceEnd, targetEnd - respectively pointers to the ends of the
                two buffers, for overflow checking only.

    These conversion functions take a ConversionFlags argument. When this
    flag is set to strict, both irregular sequences and isolated surrogates
    will cause an error.  When the flag is set to lenient, both irregular
    sequences and isolated surrogates are converted.

    Whether the flag is strict or lenient, all illegal sequences will cause
    an error return. This includes sequences such as: <F4 90 80 80>, <C0 80>,
    or <A0> in UTF-8, and values above 0x10FFFF in UTF-32. Conformant code
    must check for illegal sequences.

    When the flag is set to lenient, characters over 0x10FFFF are converted
    to the replacement character; otherwise (when the flag is set to strict)
    they constitute an error.

    Output parameters:
        The value "sourceIllegal" is returned from some routines if the input
        sequence is malformed.  When "sourceIllegal" is returned, the source
        value will point to the illegal value that caused the problem. E.g.,
        in UTF-8 when a sequence is malformed, it points to the start of the
        malformed sequence.

    Author: Mark E. Davis, 1994.
    Rev History: Rick McGowan, fixes & updates May 2001.
         Fixes & updates, Sept 2001.
*/

#ifndef POLARPHP_UTILS_CONVERT_UTF_H
#define POLARPHP_UTILS_CONVERT_UTF_H

#include <cstddef>
#include <string>

namespace polar {

// forwared declare class with namespace
namespace basic {
template <typename T> class ArrayRef;
template <typename T> class SmallVectorImpl;
class StringRef;
} // basic

namespace utils {

using polar::basic::ArrayRef;
using polar::basic::SmallVectorImpl;
using polar::basic::StringRef;

/* ---------------------------------------------------------------------
    The following 4 definitions are compiler-specific.
    The C standard does not guarantee that wchar_t has at least
    16 bits, so wchar_t is no less portable than unsigned short!
    All should be unsigned values to avoid sign extension during
    bit mask & shift operations.
------------------------------------------------------------------------ */

using Utf32 = char32_t;  /* at least 32 bits */
using Utf16 = char16_t;  /* at least 16 bits */
using Utf8 = unsigned char;   /* typically 8 bits */
using Boolean = unsigned char; /* 0 or 1 */

/* Some fundamental constants */
#define UNI_REPLACEMENT_CHAR static_cast<Utf32>(0x0000FFFD)
#define UNI_MAX_BMP static_cast<Utf32>(0x0000FFFF)
#define UNI_MAX_UTF16 static_cast<Utf32>(0x0010FFFF)
#define UNI_MAX_UTF32 static_cast<Utf32>(0x7FFFFFFF)
#define UNI_MAX_LEGAL_UTF32 static_cast<Utf32>(0x0010FFFF)

#define UNI_MAX_UTF8_BYTES_PER_CODE_POINT 4

#define UNI_UTF16_BYTE_ORDER_MARK_NATIVE  0xFEFF
#define UNI_UTF16_BYTE_ORDER_MARK_SWAPPED 0xFFFE

enum class ConversionResult
{
   ConversionOK,           /* conversion successful */
   SourceExhausted,        /* partial character in source, but hit end */
   TargetExhausted,        /* insuff. room in target for conversion */
   SourceIllegal           /* source sequence is illegal/malformed */
};

enum class ConversionFlags
{
   StrictConversion = 0,
   LenientConversion
};

ConversionResult convert_utf8_to_utf16 (
      const Utf8 **sourceStart, const Utf8 *sourceEnd,
      Utf16 **targetStart, Utf16 *targetEnd, ConversionFlags flags);

/**
 * Convert a partial Utf8 sequence to Utf32.  If the sequence ends in an
 * incomplete code unit sequence, returns \c sourceExhausted.
 */
ConversionResult convert_utf8_to_utf32_partial(
      const Utf8 **sourceStart, const Utf8 *sourceEnd,
      Utf32 **targetStart, Utf32 *targetEnd, ConversionFlags flags);

/**
 * Convert a partial Utf8 sequence to Utf32.  If the sequence ends in an
 * incomplete code unit sequence, returns \c sourceIllegal.
 */
ConversionResult convert_utf8_to_utf32(
      const Utf8 **sourceStart, const Utf8 * sourceEnd,
      Utf32 **targetStart, Utf32* targetEnd, ConversionFlags flags);

ConversionResult convert_utf16_to_utf8 (
      const Utf16 **sourceStart, const Utf16 *sourceEnd,
      Utf8 **targetStart, Utf8 *targetEnd, ConversionFlags flags);

ConversionResult convert_utf32_to_utf8 (
      const Utf32 **sourceStart, const Utf32* sourceEnd,
      Utf8 **targetStart, Utf8 *targetEnd, ConversionFlags flags);

ConversionResult convert_utf16_to_utf32 (
      const Utf16 **sourceStart, const Utf16 *sourceEnd,
      Utf32 **targetStart, Utf32* targetEnd, ConversionFlags flags);

ConversionResult convert_utf32_to_utf16 (
      const Utf32 **sourceStart, const Utf32* sourceEnd,
      Utf16 **targetStart, Utf16 *targetEnd, ConversionFlags flags);

Boolean is_legal_utf8_sequence(const Utf8 *source, const Utf8 *sourceEnd);

Boolean is_legal_utf8_string(const Utf8 **source, const Utf8 *sourceEnd);

unsigned get_num_bytes_for_utf8(Utf8 firstByte);

/*************************************************************************/
/* Below are polarphp-specific wrappers of the functions above. */

/**
 * Convert an Utf8 StringRef to UTF8, UTF16, or Utf32 depending on
 * WideCharWidth. The converted data is written to ResultPtr, which needs to
 * point to at least WideCharWidth * (Source.Size() + 1) bytes. On success,
 * ResultPtr will point one after the end of the copied string. On failure,
 * ResultPtr will not be changed, and ErrorPtr will be set to the location of
 * the first character which could not be converted.
 * \return true on success.
 */
bool convert_utf8_to_wide(unsigned wideCharWidth, StringRef source,
                          char *&resultPtr, const Utf8 *&errorPtr);

/**
* Converts a UTF-8 StringRef to a std::wstring.
* \return true on success.
*/
bool convert_utf8_to_wide(StringRef source, std::wstring &result);

/**
* Converts a UTF-8 C-string to a std::wstring.
* \return true on success.
*/
bool convert_utf8_to_wide(const char *source, std::wstring &result);

/**
* Converts a std::wstring to a UTF-8 encoded std::string.
* \return true on success.
*/
bool convert_wide_to_utf8(const std::wstring &source, std::string &result);


/**
 * Convert an Unicode code point to Utf8 sequence.
 *
 * \param Source a Unicode code point.
 * \param [in,out] ResultPtr pointer to the output buffer, needs to be at least
 * \c UNI_MAX_UTF8_BYTES_PER_CODE_POINT bytes.  On success \c ResultPtr is
 * updated one past end of the converted sequence.
 *
 * \returns true on success.
 */
bool convert_code_point_to_utf8(unsigned source, char *&resultPtr);

/**
 * Convert the first Utf8 sequence in the given source buffer to a Utf32
 * code point.
 *
 * \param [in,out] source A pointer to the source buffer. If the conversion
 * succeeds, this pointer will be updated to point to the byte just past the
 * end of the converted sequence.
 * \param sourceEnd A pointer just past the end of the source buffer.
 * \param [out] target The converted code
 * \param flags Whether the conversion is strict or lenient.
 *
 * \returns conversionOK on success
 *
 * \sa convert_utf8_to_utf32
 */
inline ConversionResult convert_utf8_sequence(const Utf8 **source,
                                              const Utf8 *sourceEnd,
                                              Utf32 *target,
                                              ConversionFlags flags)
{
   if (*source == sourceEnd) {
      return ConversionResult::SourceExhausted;
   }
   unsigned size = get_num_bytes_for_utf8(**source);
   if ((ptrdiff_t)size > sourceEnd - *source) {
      return ConversionResult::SourceExhausted;
   }
   return convert_utf8_to_utf32(source, *source + size, &target, target + 1, flags);
}

/**
 * Returns true if a blob of text starts with a UTF-16 big or little endian byte
 * order mark.
 */
bool has_utf16_byte_order_mark(ArrayRef<char> srcBytes);

/**
 * Converts a stream of raw bytes assumed to be UTF16 into a Utf8 std::string.
 *
 * \param [in] SrcBytes A buffer of what is assumed to be UTF-16 encoded text.
 * \param [out] Out Converted UTF-8 is stored here on success.
 * \returns true on success
 */
bool convert_utf16_to_utf8_string(ArrayRef<char> srcBytes, std::string &outStr);

/**
* Converts a UTF16 string into a Utf8 std::string.
*
* \param [in] Src A buffer of UTF-16 encoded text.
* \param [out] Out Converted UTF-8 is stored here on success.
* \returns true on success
*/
bool convert_utf16_to_utf8_string(ArrayRef<Utf16> srcStr, std::string &outStr);

/**
 * Converts a UTF-8 string into a UTF-16 string with native endianness.
 *
 * \returns true on success
 */
bool convert_utf8_to_utf16_string(StringRef srcStr,
                                  SmallVectorImpl<Utf16> &destStr);

} // utils

#if defined(_WIN32)
namespace sys {
namespace windows {
std::error_code utf8_to_utf16(StringRef utf8, SmallVectorImpl<wchar_t> &utf16);
/// Convert to UTF16 from the current code page used in the system
std::error_code cur_cp_to_utf16(StringRef utf8, SmallVectorImpl<wchar_t> &utf16);
std::error_code utf16_to_utf8(const wchar_t *utf16, size_t utf16_len,
                              SmallVectorImpl<char> &utf8);
/// Convert from UTF16 to the current code page used in the system
std::error_code utf16_to_cur_cp(const wchar_t *utf16, size_t utf16_len,
                                SmallVectorImpl<char> &utf8);
} // namespace windows
} // namespace sys
#endif

} //polar

#endif // POLARPHP_UTILS_CONVERT_UTF_H
